import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter_wan_android/application.dart';
import 'package:flutter_wan_android/arch/net/code.dart';
import 'package:flutter_wan_android/arch/ui/loading.dart';
import 'package:flutter_wan_android/arch/ui/toast.dart';
import 'package:flutter_wan_android/routes/route_util.dart';
import 'net_config.dart';
import 'result_data.dart';

class HttpManager {
  static HttpManager _instance = HttpManager._internal();

  Dio? _dio;

  factory HttpManager() => _instance;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal({String baseUrl = NetConfig.BASE_URL}) {
    if (null == _dio) {
      _dio = Dio(
        BaseOptions(
          baseUrl: baseUrl,
          connectTimeout: NetConfig.TIME_OUT,
          receiveTimeout: NetConfig.TIME_OUT,
          sendTimeout: NetConfig.TIME_OUT,
          // headers: {"Access-Control-Allow-Origin": "*"}, // TODO 在这里添加 headers
          //请求的Content-Type，默认值是"application/json; charset=utf-8",Headers.formUrlEncodedContentType会自动编码请求体.
          contentType: Headers.formUrlEncodedContentType,
        ),
      );

      //Fiddler抓包设置代理
      // (_dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
      //     (client) {
      //   // client.findProxy = (url) {
      //   //   return "PROXY 10.39.1.102:8888";
      //   // };
      //
      //   //抓Https包设置  信任所有https证书
      //   client.badCertificateCallback =
      //       (X509Certificate cert, String host, int port) => true;
      // };

      // 添加想要的拦截器
//       _dio?.interceptors.add(new ResponseInterceptors());
      _dio?.interceptors
        // ?..add(CookieManager(CookieJar()))
        ?..add(CookieManager(Application.cookieJar))
        ..add(LogInterceptor(responseBody: true, requestBody: true)); // 日志打印
    }
  }

  ///获取实例 并可以重新指定baseurl
  static HttpManager instance({String baseUrl = NetConfig.BASE_URL}) {
    var oldBaseUrl = _instance._dio?.options.baseUrl;

    if (oldBaseUrl != baseUrl) {
      // 之前设定的baseUrl 和 新指定的不一样才设置
      _instance._dio?.options.baseUrl = baseUrl;
    }
    return _instance;
  }

  ///通用的GET请求
  get(api, {params, withLoading = true}) async {
    if (withLoading) LoadingUtil.show();

    try {
      Response response = await _dio!.get(api, queryParameters: params);
      return _doResponse(response);
    } catch (e) {
      return _doDioError(e);
    } finally {
      if (withLoading) LoadingUtil.hide();
    }
  }

  ///通用的POST请求
  post(api, {params, withLoading = true}) async {
    if (withLoading) LoadingUtil.show();

    try {
      Response response = await _dio!.post(api, data: params);
      return _doResponse(response);
    } catch (e) {
      return _doDioError(e);
    } finally {
      if (withLoading) LoadingUtil.hide();
    }
  }
}

/// 处理 dio 请求成功后  网络数据解包
_doResponse(Response response) {
  if (response.statusCode == 200) {
    // 请求成功
    var code = response.data["errorCode"];
    var msg = response.data["errorMsg"];

    if (code == 0) {
      // TODO
      // 处理业务逻辑 成功
      // 解包后的data
      var realData = response.data["data"];
      return ResultData(realData, code, msg, true);
    } else {
      // 没登录
      if (code == Code.NOT_LOGIN) {
        ToastUtil.show("请先登录！");
        
        if(!Application.isLoginPage){
          RouteUtil.toLoginPage();
          Application.isLoginPage = true;
        }
        return;
      }

      // 业务逻辑 失败
      return ResultData(null, code, msg, false);
    }
  } else {
    return ResultData(
      null,
      response.statusCode ?? 10086,
      response.statusMessage ?? "未知错误",
      false,
    );
  }
}

/// 处理 dio 请求异常
_doDioError(e) {
  if (e.type == DioErrorType.connectTimeout ||
      e.type == DioErrorType.receiveTimeout) {
    return ResultData(null, 10087, "网络超时", false);
  }

  // 这里可以 分出 网络异常，超时等错误
  return ResultData(null, 10086, e, false);
}
